package com.ltwc.lttv.api


import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager


class MyApiClient() {
    //private val infoUrl = "http://192.168.125.161:8080/"
    private val infoUrl = "http://imengu.cn:9777/"
    //private val infoUrl = "http://192.168.55.4:8080/"
    private var okHttpClient = getUnsafeOkHttpClient()

    val yspInfoService: YSPInfoService by lazy {
        var client = okHttpClient;
        client = client.newBuilder().addInterceptor(LTInterceptor()).build()
        Retrofit.Builder()
            .baseUrl(infoUrl)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build().create(YSPInfoService::class.java)
    }

    private fun getUnsafeOkHttpClient(): OkHttpClient {
        try {
            val trustAllCerts: Array<TrustManager> = arrayOf(
                object : X509TrustManager {
                    override fun checkClientTrusted(
                        chain: Array<out java.security.cert.X509Certificate>?,
                        authType: String?
                    ) {
                    }

                    override fun checkServerTrusted(
                        chain: Array<out java.security.cert.X509Certificate>?,
                        authType: String?
                    ) {
                    }

                    override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
                        return emptyArray()
                    }
                }
            )

            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, java.security.SecureRandom())

            return OkHttpClient.Builder()
                .sslSocketFactory(sslContext.socketFactory, trustAllCerts[0] as X509TrustManager)
                .hostnameVerifier { _, _ -> true }
                .dns(DnsCache())
                .build()

        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}
